package upicgame.game.dao.impl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import upicgame.entity.Game;
import upicgame.game.dao.GameDao;

import javax.annotation.Resource;
import java.util.List;

/*
 *Created by GHW
 *Description:实现类，实现gameDao
 *2019/12/17 10:48
 */
@Repository
public class GameDaoImpl implements GameDao {
    @Resource
    private SessionFactory sessionFactory;

    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    //增加游戏
    @Override
    public Game addGame(Game game) {
        getSession().save(game);
        return game;
    }

    //id单查游戏
    @Override
    public Game findGameById(Integer id) {
        String hql = "from Game where id=?";
        return (Game) getSession().createQuery(hql).setParameter(0, id).uniqueResult();
    }

    //name单查游戏
    @Override
    public Game findGameByName(String name) {
        String hql = "from Game where name=?";
        return (Game) getSession().createQuery(hql).setParameter(0, name).uniqueResult();
    }

    //游戏全查
    //禁止警告("unchecked")
    @SuppressWarnings("unchecked")
    @Override
    public List<Game> findAllGame() {

        Query query = this.getSession().createQuery("from Game");
        return (List<Game>) query.list();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Game> findAllGameByPage(Integer pageNum, Integer pageSize) {

        //获取数据库总条数
        Query query = this.getSession().createQuery("from Game ");
        //从第几个开始拿
        query.setFirstResult((pageNum - 1) * pageSize);
        //每页拿几个
        query.setMaxResults(pageSize);
        //返回list结果集
        return (List<Game>) query.list();
    }

    //游戏搜索带分页（模糊搜索）
    @SuppressWarnings("unchecked")
    @Override
    public List<Game> findAllGameByPageWithFuzzy(Integer pageNum, Integer pageSize, String gameName) {
        //模糊查询游戏名称
        String hql = "from Game where name like '%" + gameName + "%'";
        Query query = this.getSession().createQuery(hql);

        //从第几个开始拿
        query.setFirstResult((pageNum - 1) * pageSize);
        //每页拿几个
        query.setMaxResults(pageSize);
        //返回list结果集
        return (List<Game>) query.list();
    }

    //查找总条数
    public int findCount() {
        Query query = this.getSession().createQuery("select count (*) from Game");
//        Long转换成int，需要先将uniqueResult()对象转成Long，再将Long转成String，再转成int
        Long result = (Long) query.uniqueResult();
        return (Integer.parseInt(String.valueOf(result)));
    }

    //修改游戏信息
    @Override
    public void updateGameInfo(Game game) {
        getSession().update(game);
    }

    //删除游戏
    @Override
    public void deleteGame(Game game) {
        getSession().delete(game);
    }
}
